<!--
 * @Author: 冕上 cxm66888@163.com
 * @Date: 2025-01-01 00:00:00
 * @LastEditors: 冕上 cxm66888@163.com
 * @LastEditTime: 2025-01-01 00:00:00
 * @Description: 会员折扣策略管理
 * 
 * Copyright (c) 2025 by xiaoMing.Cao, All Rights Reserved. 
-->
<template>
  <div class="app-container">
    <!-- 统计信息 -->
    <div class="stats-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card" @click="filterByStatus('')">
            <div class="stats-item">
              <div class="stats-number">{{ stats.total || 0 }}</div>
              <div class="stats-label">总策略数</div>
              <div class="stats-tip">点击查看全部</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" @click="filterByStatus(true)">
            <div class="stats-item">
              <div class="stats-number">{{ stats.enabled || 0 }}</div>
              <div class="stats-label">已启用</div>
              <div class="stats-tip">点击筛选启用状态</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" @click="filterByStatus(false)">
            <div class="stats-item">
              <div class="stats-number">{{ stats.disabled || 0 }}</div>
              <div class="stats-label">已禁用</div>
              <div class="stats-tip">点击筛选禁用状态</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" @click="filterByType('active')">
            <div class="stats-item">
              <div class="stats-number">{{ stats.active || 0 }}</div>
              <div class="stats-label">生效中</div>
              <div class="stats-tip">点击筛选生效策略</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-container">
      <el-input v-model="listQuery.strategyId" placeholder="请输入策略ID" style="width: 200px" class="filter-item" @keyup.enter="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="选择类型" clearable style="width: 150px" class="filter-item">
        <el-option label="开通优惠" value="open" />
        <el-option label="续费优惠" value="renew" />
      </el-select>
      <el-select v-model="listQuery.userCondition" placeholder="触发条件" clearable style="width: 180px" class="filter-item">
        <el-option label="注册天数" value="register_day" />
        <el-option label="访问过VIP页" value="visited_vip" />
      </el-select>
      <el-select v-model="listQuery.isEnabled" placeholder="状态" clearable style="width: 120px" class="filter-item">
        <el-option label="启用" :value="true" />
        <el-option label="禁用" :value="false" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="Search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" type="warning" icon="Refresh" @click="handleRefresh">重置刷新</el-button>
      <el-button class="filter-item" type="success" icon="Plus" @click="handleCreate">新增策略</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      v-loading="listLoading" 
      :data="list" 
      element-loading-text="Loading..." 
      border 
      fit 
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" type="index" label="序号" width="80">
        <template #default="scope">
          {{ (listQuery.pageIndex - 1) * listQuery.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="策略ID" align="center" width="120">
        <template #default="scope">
          <span>{{ scope.row.strategyId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" width="120">
        <template #default="scope">
          <el-tag :type="getTypeTagType(scope.row.type)">
            {{ getTypeLabel(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="折扣比例" align="center" width="120">
        <template #default="scope">
          <span class="discount-text">{{ (scope.row.discount * 10).toFixed(1) }}折</span>
        </template>
      </el-table-column>
      <el-table-column label="生效时间" align="center" width="200">
        <template #default="scope">
          <div>{{ formatDate(scope.row.startTime) }}</div>
          <div class="time-separator">至</div>
          <div>{{ formatDate(scope.row.endTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="触发条件" align="center" width="180">
        <template #default="scope">
          <el-tag size="small" type="info">
            {{ getUserConditionLabel(scope.row.userCondition, scope.row.registerDays) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isEnabled"
            :active-value="true"
            :inactive-value="false"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="total > 0"
      style="margin-top: 15px; background: #fff; padding: 10px"
      :page-size="listQuery.pageSize"
      @current-change="handlePageChange"
      background
      layout="prev, pager, next, total"
      :total="total"
    />

    <!-- 批量操作 -->
    <div v-if="selectedItems.length > 0" class="batch-actions">
      <el-button type="danger" size="small" @click="handleBatchDelete">批量删除 ({{ selectedItems.length }})</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getMemberDiscountList,
  deleteMemberDiscount,
  toggleMemberDiscountStatus,
  batchDeleteMemberDiscount,
  getMemberDiscountStats
} from '@/api/memberDiscount';

const router = useRouter();

// 响应式数据
const list = ref([]);
const total = ref(0);
const listLoading = ref(true);
const selectedItems = ref([]);
const stats = ref({
  total: 0,
  enabled: 0,
  disabled: 0,
  active: 0
});

// 查询参数
const listQuery = reactive({
  pageIndex: 1,
  pageSize: 20,
  strategyId: '',
  type: '',
  userCondition: '',
  isEnabled: ''
});

// 获取列表数据
const getList = async () => {
  listLoading.value = true;
  try {
    const response = await getMemberDiscountList(listQuery);
    list.value = response.data.list || [];
    total.value = response.data.total || 0;
  } catch (error) {
    console.error('获取折扣策略列表失败:', error);
    ElMessage.error('获取折扣策略列表失败');
  } finally {
    listLoading.value = false;
  }
};

// 获取统计信息
const getStats = async () => {
  try {
    const response = await getMemberDiscountStats();
    stats.value = response.data || {};
  } catch (error) {
    console.error('获取统计信息失败:', error);
  }
};

// 搜索
const handleFilter = () => {
  listQuery.pageIndex = 1;
  getList();
};

// 重置刷新
const handleRefresh = () => {
  Object.assign(listQuery, {
    pageIndex: 1,
    pageSize: 20,
    strategyId: '',
    type: '',
    userCondition: '',
    isEnabled: ''
  });
  getList();
  getStats();
};

// 按状态筛选
const filterByStatus = (status) => {
  listQuery.isEnabled = status;
  listQuery.pageIndex = 1;
  getList();
};

// 按类型筛选
const filterByType = (type) => {
  listQuery.type = type;
  listQuery.pageIndex = 1;
  getList();
};

// 分页变化
const handlePageChange = (page) => {
  listQuery.pageIndex = page;
  getList();
};

// 新增
const handleCreate = () => {
  router.push('/member-discount/create');
};

// 编辑
const handleUpdate = (row) => {
  router.push(`/member-discount/edit/${row._id}`);
};

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个折扣策略吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await deleteMemberDiscount(row._id);
    ElMessage.success('删除成功');
    getList();
    getStats();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 状态切换
const handleStatusChange = async (row) => {
  try {
    await toggleMemberDiscountStatus(row._id, row.isEnabled);
    ElMessage.success(row.isEnabled ? '启用成功' : '禁用成功');
    getStats();
  } catch (error) {
    console.error('状态切换失败:', error);
    ElMessage.error('状态切换失败');
    // 恢复原状态
    row.isEnabled = !row.isEnabled;
  }
};

// 选择变化
const handleSelectionChange = (selection) => {
  selectedItems.value = selection;
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要删除的项目');
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedItems.value.length} 个折扣策略吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const ids = selectedItems.value.map(item => item._id);
    await batchDeleteMemberDiscount(ids);
    ElMessage.success('批量删除成功');
    getList();
    getStats();
    selectedItems.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }
};

// 工具函数
const getTypeLabel = (type) => {
  const typeMap = {
    'open': '开通优惠',
    'renew': '续费优惠'
  };
  return typeMap[type] || type;
};

const getTypeTagType = (type) => {
  const typeMap = {
    'open': 'success',
    'renew': 'warning'
  };
  return typeMap[type] || 'info';
};

const getUserConditionLabel = (condition, registerDays) => {
  if (condition === 'register_day') {
    return `注册${registerDays || 1}天`;
  } else if (condition === 'visited_vip') {
    return '访问过VIP页';
  }
  return condition || '未知';
};

const formatDate = (timestamp) => {
  if (!timestamp) return '';
  // 如果是时间戳（数字），直接转换；如果是字符串，先转换
  const date = typeof timestamp === 'number' ? new Date(timestamp) : new Date(timestamp);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 生命周期
onMounted(() => {
  getList();
  getStats();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.stats-container {
  margin-bottom: 20px;
  
  .stats-card {
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    .stats-item {
      text-align: center;
      
      .stats-number {
        font-size: 24px;
        font-weight: bold;
        color: #409eff;
        margin-bottom: 8px;
      }
      
      .stats-label {
        font-size: 14px;
        color: #606266;
        margin-bottom: 4px;
      }
      
      .stats-tip {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

.filter-container {
  padding-bottom: 10px;
  
  .filter-item {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.discount-text {
  font-weight: bold;
  color: #e6a23c;
}

.time-separator {
  font-size: 12px;
  color: #909399;
  margin: 2px 0;
}

.batch-actions {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>

